﻿///////////////////////////////////////////////////////////////////////////////
// File:        ConnectionInputStream.cc
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#include "nio/net/ConnectionInputStream.hpp"
using namespace nio::net;

#define __INN_MIN(a, b) ((a) > (b)) ? (b) : (a)

#define RECV_BUFF_SIZE  0x4000

ConnectionInputStream::ConnectionInputStream(Socket& sock, unsigned int size)
    : ConnectionStream(sock, size)
    , recvBytsFN_()
{

}

ConnectionInputStream::ConnectionInputStream(Socket& sock, boost::shared_array<char> buff, unsigned int size)
    : ConnectionStream(sock, buff, size)
    , recvBytsFN_()
{

}

ConnectionInputStream::~ConnectionInputStream()
{

}

int ConnectionInputStream::fill()
{
    if (space() == 0)
        return 0;

    char buff[RECV_BUFF_SIZE];
    unsigned int bytsReadAll = 0;

    while (space() > 0)
    {
        int bytsRead = sock_.read(buff, __INN_MIN(RECV_BUFF_SIZE, space()));
        if (bytsRead < 0)
        {
            if (bytsRead == SOCKET_ERROR)
                return SOCKET_ERROR;
            else if (bytsRead == SOCKET_ERROR_WOULDBLOCK)
                break;
        }
        else if (bytsRead == 0)
        {
            return SOCKET_ERROR;
        }

        write(buff, (unsigned int)bytsRead);
        bytsReadAll += (unsigned int)bytsRead;
    }

    recvBytsFN_(bytsReadAll);
    return bytsReadAll;
}


